package com.example.petcare.service.serviceImpl;

import com.example.petcare.exception.PetException;
import com.example.petcare.mapper.HostMapper;
import com.example.petcare.mapper.PetMapper;
import com.example.petcare.pojo.HostDemand;
import com.example.petcare.pojo.Pet;
import com.example.petcare.service.PetService;
import com.example.petcare.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class PetServiceImpl implements PetService {

    @Autowired
    private PetMapper petMapper;

    @Autowired
    private HostMapper hostMapper;

    // 添加宠物
    @Override
    public void addPet(Pet pet) {

        Map<String,Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("userId");

        // 判断这个宠物信息是否完整，如果不完整，抛出异常
        if(pet.getPetName() == null || pet.getPetType() == null || pet.getPetAge() == null || pet.getPetGender()==null|| pet.getPetWeight() == null|| pet.getPetPic() == null){
            throw new PetException("宠物信息不完整");
        }

        pet.setUserId(userId);

        petMapper.addPet(pet);
    }


    // 删除宠物
    @Override
    public void deletePet(Integer petId) {

        // 判断宠物是否有关联的委托需求,根据宠物id查询委托需求列表
        List<HostDemand> hostDemands = hostMapper.findByPetId(petId);

        // 如果有关联的委托需求，抛出异常
        if(hostDemands.size() > 0){
            throw new PetException("宠物有关联的委托需求，不能删除");
        }


        petMapper.deletePet(petId);
    }

    // 更新宠物信息
    @Override
    public void updatePet(Pet pet) {

        // 检查这个宠物是否和委托关联，如果关联，抛出异常
        List<HostDemand> hostDemands = hostMapper.findByPetId(pet.getPetId());
        if(hostDemands.size() > 0){
            throw new PetException("宠物有关联的委托需求，不能修改");
        }

        petMapper.updatePet(pet);
    }

    // 获取宠物详情
    @Override
    public Pet findById(Integer petId) {
        Pet pet = petMapper.findById(petId);
        return pet;
    }

    // 获取用户宠物列表
    @Override
    public List<Pet> list() {
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("userId");
        return petMapper.list(userId);
    }



}
